/**
 * module:  检疫记录
 * avator:   渣
 * table:  nc_quarantine,nc_livestock,nc_pasture,nc_house
 */
var express = require('express');
var router = express.Router();
var zSend = require('./controller');

const db = require('../../../db/db');

router.get('/list', (req, res, next) => {
    const { currentPage = 1, pageSize = 5, searchValue = '', pastureId = '', houseId = '' } = req.query;
    if (isNaN(currentPage) || isNaN(pageSize)) {
        return res.send(zSend('参数错误', 400));
    }

    const parsedPage = parseInt(currentPage);
    const parsedSize = parseInt(pageSize);
    
    if (parsedPage <= 0 || parsedSize <= 0) {
        return res.send(zSend('参数错误', 400));
    }

    // 构建基础查询条件
    let whereClause = '';
    const values = [];
    
    if (searchValue) {
        whereClause += ' AND (l.F_Title LIKE ? OR l.F_IMEI LIKE ?)';
        values.push(`%${searchValue}%`, `%${searchValue}%`);
    }
    
    if (pastureId) {
        whereClause += ' AND l.F_Org_Id = ?';
        values.push(pastureId);
    }
    
    if (houseId) {
        whereClause += ' AND l.F_HouseId = ?';
        values.push(houseId);
    }

    // 统计总数的SQL（防止SQL注入）
    const countSql = `
        SELECT COUNT(*) as total
        FROM nc_quarantine as q 
        left JOIN nc_livestock as l ON q.F_liveid = l.F_Id
        left JOIN nc_pasture as p ON l.F_Org_Id = p.F_Id
        left JOIN nc_house as h ON l.F_HouseId = h.F_Id
        WHERE 1=1 ${whereClause}
    `;

    db.query(countSql, values, (countErr, countData) => {
        if (countErr) {
            console.error('统计总数失败:', countErr);
            return res.send(zSend('服务器内部错误', 500));
        }

        const total = countData[0]?.total || 0;
        const totalPages = Math.max(1, Math.ceil(total / parsedSize));
        const effectivePage = Math.min(parsedPage, totalPages);
        const offset = (effectivePage - 1) * parsedSize;

        // 查询列表数据的SQL（防止SQL注入）
        const listSql = `
            SELECT l.F_Title, l.F_IMEI, p.F_Title as pastureTitle, h.F_Title as houseTitle, q.*
            FROM nc_quarantine as q 
            left JOIN nc_livestock as l ON q.F_liveid = l.F_Id
            left JOIN nc_pasture as p ON l.F_Org_Id = p.F_Id
            left JOIN nc_house as h ON l.F_HouseId = h.F_Id
            WHERE 1=1 ${whereClause}
            ORDER BY q.F_CreateTime DESC
            LIMIT ? OFFSET ?
        `;
        
        const listValues = [...values, parsedSize, offset];

        db.query(listSql, listValues, (listErr, listData) => {
            if (listErr) {
                console.error('查询列表失败:', listErr);
                return res.send(zSend('服务器内部错误', 500));
            }

            res.send(zSend({
                list: listData || [],
                total,
            }));
        });
    });
});
// 配种记录添加
router.post('/add', (req, res, next) => {
    const { F_liveid, F_Title,F_Stand,F_UserName,F_Phone,F_Address,F_Level,F_Remark,F_ResultImage,F_StTime} = req.body;
    if (!F_liveid || !F_Title || !F_Stand || !F_UserName || !F_Phone || !F_Address || !F_Level || !F_Remark || !F_ResultImage|| !F_StTime) {
        res.send(zSend('参数错误', 400))
    }
    const F_Id = Date.now();
    const F_CreateTime = new Date().toLocaleString();
    const sql = `
        INSERT INTO nc_quarantine (
            F_Id,F_liveid, F_Title,F_Stand,F_UserName,F_Phone,F_StTime,F_Address,F_Level,F_Remark,F_ResultImage,F_CreateTime
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `
    db.query(sql, [F_Id,F_liveid, F_Title,F_Stand,F_UserName,F_Phone,F_StTime,F_Address,F_Level,F_Remark,F_ResultImage,F_CreateTime], (err, data) => {
        if (!data) {
            res.send(zSend('服务器内部错误', 500))
        } else {
            res.send(zSend('添加成功'))
        }
    })
})

// 配种记录修改
router.post('/edit', (req, res, next) => {
    const { F_Id, F_liveid, F_Title,F_Stand,F_UserName,F_Phone,F_Address,F_Level,F_Remark,F_ResultImage,F_StTime} = req.body;
    if (!F_Id || !F_liveid || !F_Title || !F_Stand || !F_UserName || !F_Phone || !F_Address || !F_Level || !F_Remark || !F_ResultImage|| !F_StTime) {
        res.send(zSend('参数错误', 400))
    }
    const sql = `
        UPDATE nc_quarantine SET F_liveid = ?, F_Title = ?, F_Stand = ?, F_UserName = ?, F_Phone = ?, F_Address = ?, F_Level = ?, F_Remark = ?, F_ResultImage = ?, F_StTime = ? WHERE F_Id = ?
    `
    db.query(sql, [F_liveid, F_Title,F_Stand,F_UserName,F_Phone,F_Address,F_Level,F_Remark,F_ResultImage,F_StTime, F_Id], (err, data) => {
        if (!data) {
            res.send(zSend('服务器内部错误', 500))
        } else {
            res.send(zSend('修改成功'))
        }
    })
})
// 配种记录删除
router.post('/delete', (req, res, next) => {
    const { F_Id } = req.body;
    if (!F_Id) {
        res.send(zSend('参数错误', 400))
    }
    const sql = `
        delete from nc_quarantine where F_Id='${F_Id}'
    `
    db.query(sql, (err, data) => {
        if (!data) {
            res.send(zSend('服务器内部错误', 500))
        } else {
            res.send(zSend('删除成功'))
        }
    })
})

module.exports = router;